/*
Copyright 2022 Flant JSC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package hooks

import (
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"

	. "github.com/deckhouse/deckhouse/testing/hooks"
)

var _ = Describe("Modules :: prometheus :: hooks :: generate_istio_mtls_cert ::", func() {
	f := HookExecutionConfigInit(`
{
  "global":
    {"discovery":
       { "clusterDomain":"cluster.local"}
    },
  "prometheus": {
     "internal":{
        "prometheusMain":{},
        "prometheusLongterm":{},
        "prometheusScraperIstioMTLS":{}
     }
  }
}`, "")

	var istioCASecret = `
---
apiVersion: v1
data:
  ca-cert.pem: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURIRENDQWdTZ0F3SUJBZ0lVYjJJMmx6RkVOYWFKMG5SeFJOempPUXdXN0JBd0RRWUpLb1pJaHZjTkFRRUwKQlFBd0pqRVJNQThHQTFVRUNoTUlaRGd0YVhOMGFXOHhFVEFQQmdOVkJBTVRDR1E0TFdsemRHbHZNQjRYRFRJeQpNRGd4T1RJeE5ERXdNRm9YRFRNeU1EZ3hOakl4TkRFd01Gb3dKakVSTUE4R0ExVUVDaE1JWkRndGFYTjBhVzh4CkVUQVBCZ05WQkFNVENHUTRMV2x6ZEdsdk1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQkNnS0MKQVFFQXlFd0RKWkRjdkVFUUNrQm5pZjlsWGR4VHU4TDQyc0RheUJVTmYzM2FTVVhwWmxRVU5wTCttcElhanpabAp4YVpuZXZqSjFFeUZCQVBaQ0tGMj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scraper-istio-mtls
  namespace: d8-monitoring
type: kubernetes.io/tls
`

	var brokenMTLSCertSecret = `
---
apiVersion: v1
data:
  tls.crt: MTExCg==
  tls.key: MTExCg==
kind: Secret
metadata:
  name: prometheus-scraper-istio-mtls
  namespace: d8-monitoring
type: kubernetes.io/tls
	`

	Context("Empty cluster and minimal settings", func() {
		BeforeEach(func() {
			f.BindingContexts.Set(f.KubeStateSet(``))
			f.RunHook()
		})

		It("Hook must execute successfully", func() {
			Expect(f).To(ExecuteSuccessfully())
			Expect(f.ValuesGet(mTLSCrtPath).Exists()).To(BeFalse())
			Expect(f.ValuesGet(mTLSKeyPath).Exists()).To(BeFalse())
		})
	})

	Context("Istio CA secret absent, but mTLS secret exits", func() {
		BeforeEach(func() {
			f.BindingContexts.Set(f.KubeStateSet(expiredMTLSCertSecret))
			f.RunHook()
		})

		It("Hook must execute successfully", func() {
			Expect(f).To(ExecuteSuccessfully())
			Expect(f.ValuesGet(mTLSCrtPath).Exists()).To(BeFalse())
			Expect(f.ValuesGet(mTLSKeyPath).Exists()).To(BeFalse())
		})
	})

	Context("Istio CA secret exists and mTLS secret exits and valid", func() {
		BeforeEach(func() {
			f.BindingContexts.Set(f.KubeStateSet(istioCASecret + MTLSCertSecretValidFor100Years))
			f.RunHook()

		})
		It("Hook must execute successfully", func() {
			Expect(f).To(ExecuteSuccessfully())
			Expect(f.ValuesGet(mTLSCrtPath).Exists()).To(BeTrue())
			Expect(f.ValuesGet(mTLSKeyPath).Exists()).To(BeTrue())
			cert, err := base64.StdEncoding.DecodeString(f.KubernetesResource("Secret", "d8-monitoring", "prometheus-scraper-istio-mtls").Field(`data.tls\.crt`).String())
			Expect(err).ShouldNot(HaveOccurred())
			Expect(f.ValuesGet(mTLSCrtPath).String()).To(BeEquivalentTo(cert))
			key, err := base64.StdEncoding.DecodeString(f.KubernetesResource("Secret", "d8-monitoring", "prometheus-scraper-istio-mtls").Field(`data.tls\.key`).String())
			Expect(err).ShouldNot(HaveOccurred())
			Expect(f.ValuesGet(mTLSKeyPath).String()).To(BeEquivalentTo(key))

		})
	})

	DescribeTable("Istio CA secret exists, but some issues with mTLS secert", func(objectsYAMLs string) {
		f.BindingContexts.Set(f.KubeStateSet(objectsYAMLs))
		f.RunHook()

		Expect(f).To(ExecuteSuccessfully())
		Expect(f.ValuesGet(mTLSCrtPath).Exists()).To(BeTrue())
		Expect(f.ValuesGet(mTLSKeyPath).Exists()).To(BeTrue())

		// checks for prometheus scraper mTLS cert
		mTLSCert := f.ValuesGet(mTLSCrtPath).String()

		block, _ := pem.Decode([]byte(mTLSCert))
		cert, err := x509.ParseCertificate(block.Bytes)
		Expect(err).ShouldNot(HaveOccurred())
		Expect(cert.IsCA).To(BeFalse())

		Expect(cert.URIs[0].Scheme).To(Equal("spiffe"))
		Expect(cert.URIs[0].Host).To(Equal("cluster.local"))
		Expect(cert.URIs[0].Path).To(Equal("/ns/d8-monitoring/sa/prometheus"))

		istioCA, err := base64.StdEncoding.DecodeString(f.KubernetesResource("Secret", "d8-istio", "cacerts").Field(`data.ca-cert\.pem`).String())
		Expect(err).ShouldNot(HaveOccurred())

		certPool := x509.NewCertPool()
		ok := certPool.AppendCertsFromPEM(istioCA)
		Expect(ok).To(BeTrue())

		clientOpts := x509.VerifyOptions{
			Roots:       certPool,
			KeyUsages:   []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
			CurrentTime: time.Now().Add(time.Hour * 8030), // ~ 11 month
		}
		_, err = cert.Verify(clientOpts)
		Expect(err).ShouldNot(HaveOccurred())

		serverOpts := x509.VerifyOptions{
			Roots:       certPool,
			KeyUsages:   []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, // wrong key usage
			CurrentTime: time.Now().Add(time.Hour * 8030),               // ~ 11 month
		}
		_, err = cert.Verify(serverOpts)
		Expect(err).Should(HaveOccurred())

	},
		Entry("There is no mTLS secret", istioCASecret),
		Entry("mTLS secret is expired", istioCASecret+expiredMTLSCertSecret),
		Entry("mTLS secret signed with old CA", istioCASecretNew+MTLSCertSecretValidFor100Years),
		Entry("mTLS secret broken", istioCASecret+brokenMTLSCertSecret),
	)

})
